import axios from 'axios'
import Message from 'iview/src/components/message'
import Notice from 'iview/src/components/notice'
import Modal from 'iview/src/components/modal'

// https://www.kancloud.cn/yunye/axios/234845 详细配置
let notice = null
axios.interceptors.request.use(
  config => {
    let userToken = localStorage.getItem('userToken')
    if (userToken !== null) {
      config.headers['token'] = userToken
    }
    
    config.params = {
      _t: Date.parse(new Date()) / 1000,
      ...config.params
    }
    return config
  }, error => {
    return Promise.reject(error)
  }
)
axios.interceptors.response.use(function (response) {
  // token 已过期，重定向到登录页面
  let code = response.data.code  
  return response.data  
}, error => {
  if (error.response) {
    let message = error.response.data.msg
    switch (error.response.status) {
      case 401:
        Message.warning({
          content: message
        })
        break
      case 403:
        Notice.destroy('authc_error')
        if (!notice) {
          Notice.info({
            title: '温馨提示',
            desc: '未登入',
            duration: 0,
            name: 'authc_error'
          })
        }
        router.replace({
          path: '/login',
          query: {redirect: router.currentRoute.fullPath}
        })
        break
      case 500:
        Modal.error({
          render: (h) => {
            return h('div', {}, [
              h('Button', {
                props: {
                  type: 'error',
                  long: true,
                  icon: 'information-circled',
                  size: 'large'
                },
                style: {
                  marginBottom: '10px'
                }
              }, message),
              h('Input', {
                props: {
                  type: 'textarea',
                  rows: 10,
                  value: error.response.data.result.exception
                }
              })
            ]
            )
          }
        })
        break
      case 504:
        Message.warning({
          content: '网络连接超时'
        })
        break
      default:
        Message.warning({
          content: '服务器繁忙，请稍候再试'
        })
    }
  }
  return Promise.reject(error)
})
export default axios
